package com.example.spider.provider.why10w.whys100000;

import cn.hutool.core.util.ReUtil;
import com.example.spider.provider.why10w.AbstractWhy10wDetailResultHandler;
import com.example.spider.provider.why10w.dto.Why10wDetailTask;
import com.example.spider.provider.why10w.dto.WhyImageInfo;
import com.example.spider.provider.why10w.dto.WhyTaskResult;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理 whys100000 详情页结果
 *
 * @author lym
 */
@Slf4j
@Component
public class Whys100000DetailResultHandler extends AbstractWhy10wDetailResultHandler {

    /**
     * handle
     */
    @Override
    public void doHandle(Why10wDetailTask task, String html) {
        // 要解析的太多了，先截取期望部分，避免每次解析全部html
        String hasContentRegex = "id=\"f\"(.*?)id=\"g\"";
        List<String> contentStr = ReUtil.findAllGroup1(hasContentRegex, html);
        if (contentStr.isEmpty()) {
            // 结束了
            log.error("whys100000Detail invalid. Task:{}", task);
            return;
        }

        String content = contentStr.get(0);

        String id = ReUtil.findAllGroup1("http://www.100000whys.com/(.*?)\\.html", task.getUrl()).get(0);

        String title = task.getTitle();

        // 类别，可能多个
        String categoryRegex = "<a href=\"http://www.100000whys.com/.*?\" rel=\"category tag\">(.*?)</a>";
        List<String> categoryList = ReUtil.findAllGroup1(categoryRegex, content);

        // 标签，可能多个
        String tagRegex = "rel=\"tag\">(.*?)</a>";
        List<String> tagList = ReUtil.findAllGroup1(tagRegex, content);

        // 文章
        String contentRegex = "<div class=\"n_n\">(.*?)<div class=\"quote\">";
        List<String> contentFindResult = ReUtil.findAllGroup1(contentRegex, content);
        String realContent = "";
        if (CollectionUtils.isEmpty(contentFindResult)) {
            // 不存在
            log.error("empty");
        } else {
            realContent = Jsoup.parse(contentFindResult.get(0)).text();
        }

        // 图片，可能多个
        List<String> imageMatchList = ReUtil.findAllGroup1("<img (.*?)>", realContent);
        List<WhyImageInfo> imageInfoList = imageMatchList == null ? Collections.emptyList() :
                imageMatchList.parallelStream().map(s -> {
                    String name = ReUtil.findAllGroup1("alt=\"(.*?)\"", s).get(0);
                    String url = ReUtil.findAllGroup1("src=\"(.*?)\"", s).get(0);
                    return WhyImageInfo.builder()
                            .name(name)
                            .url(url)
                            .build();
                }).collect(Collectors.toList());

        // 转为标准模型
        WhyTaskResult result = WhyTaskResult.builder()
                .id(id)
                .title(title)
                .url(task.getUrl())
                .categoryList(categoryList)
                .tagList(tagList)
                .imageInfoList(imageInfoList)
                .content(realContent)
                .source(task.getSource())
                .build();
        // ***********************
        // 保存
        repository.addResult(result);

        //String fileName = "F:/spider/www.100000whys.com/" + id + ".json";
        //log.debug("prepare save to file: {}" + fileName);
        //File file = FileUtil.touch(fileName);
        //FileUtil.writeString(JsonUtils.toJson(result), file, StandardCharsets.UTF_8);

        repository.saveHtml(task, html);
    }

}
